<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\Message\Repository;

use App\Repository\IRepository;
use Hyperf\Database\Model\Builder;
use Plugin\Message\Model\MessageRead;

/**
 * 消息读取状态 Repository类
 */
class MessageReadRepository extends IRepository
{
    public function __construct(
        protected readonly MessageRead $model
    )
    {
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        // 主键ID
        if (isset($params['id']) && filled($params['id'])) {
            $query->where('id', '=', $params['id']);
        }

        // 消息ID
        if (isset($params['message_id']) && filled($params['message_id'])) {
            $query->where('message_id', '=', $params['message_id']);
        }

        // 接收用户ID
        if (isset($params['user_id']) && filled($params['user_id'])) {
            $query->where('user_id', '=', $params['user_id']);
        }

        // 读取状态 1未读 2已读
        if (isset($params['status']) && filled($params['status'])) {
            $query->where('status', '=', $params['status']);
        }

        // 消息类型
        if (isset($params['type']) && filled($params['type'])) {
            $query->where('type', '=', $params['type']);
        }

        // 读取时间
        if (isset($params['read_time']) && filled($params['read_time']) && is_array($params['read_time']) && count($params['read_time']) == 2) {
            $query->whereBetween(
                'read_time',
                [$params['read_time'][0], $params['read_time'][1]]
            );
        }

        return $query;
    }

    public function apiPage(array $params = [], ?int $page = null, ?int $pageSize = null): array
    {
        $p = $this->perQuery($this->getQuery(), $params)
            ->with(['message'])
            ->paginate(
                perPage: $pageSize,
                columns: ['id', 'message_id', 'status', 'read_time', 'type'],
                pageName: static::PER_PAGE_PARAM_NAME,
                page: $page
            );
        return $this->handlePage($p);
    }

    /**
     * 批量创建消息读取记录
     * @param array $data 读取记录数据数组
     * @return bool
     */
    public function batchCreate(array $data): bool
    {
        return $this->model->newQuery()->insert($data);
    }

}